package com.example.freeengine.filetranslate.fragment.receive;

import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.freeengine.R;
import com.example.freeengine.databinding.FragmentFiletranslateReceiveBinding;
import com.example.freeengine.filetranslate.FileTranslateViewModel;
import com.example.freeengine.filetranslate.fragment.ResponseMessage;
import com.example.freeengine.filetranslate.fragment.receive.listadapter.FileTranslateReceiveListAdapter;
import com.example.freeengine.filetranslate.persistence.entity.FileTranslateProgress;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.koushikdutta.async.http.WebSocket;

import java.util.List;
import java.util.Objects;


public class FiletranslateReceiveFragment extends Fragment {

    private static final String TAG = FiletranslateReceiveFragment.class.getSimpleName();
    FragmentFiletranslateReceiveBinding viewBinding;
    FileTranslateViewModel viewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        viewBinding = FragmentFiletranslateReceiveBinding.inflate(inflater);
        return viewBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = new ViewModelProvider(requireActivity()).get(FileTranslateViewModel.class);
        Toolbar toolbar = requireActivity().findViewById(R.id.tb_filetranslate);
        toolbar.setTitle("接收");

        FileTranslateReceiveListAdapter fileTranslateReceiveListAdapter = new FileTranslateReceiveListAdapter(requireContext(), viewModel);
        viewBinding.rvFiletranslate.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayout.VERTICAL, false));
        viewBinding.rvFiletranslate.setAdapter(fileTranslateReceiveListAdapter);
        viewBinding.rvFiletranslate.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));
        viewModel.getFileTranslateRepository().findAll().observe(requireActivity(), new Observer<List<FileTranslateProgress>>() {
            @Override
            public void onChanged(List<FileTranslateProgress> fileTranslateProgresses) {
                fileTranslateReceiveListAdapter.submitList(fileTranslateProgresses);
            }
        });

        viewModel.getClientConnect().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String data) {
                if (data.length() > 2){
                    Log.i(TAG, "client id: " + data);
                    authClient(data);
                }
            }
        });

    }

    public void authClient(String uuid){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(requireContext())
                .setTitle("提示")
                .setMessage("是否接受该设备的连接请求?" + "\n" + "uuid: " + uuid)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (viewModel.getClientMap().get(uuid) == null){
                            return;
                        }
                        WebSocket webSocket = Objects.requireNonNull(viewModel.getClientMap().get(uuid)).getWebSocket();
                        ResponseMessage responseMessage = new ResponseMessage.Builder().setType(2).setContent("通过").build();
                        ObjectMapper objectMapper = new ObjectMapper();
                        try {
                            webSocket.send(objectMapper.writeValueAsString(responseMessage));
                            viewModel.getAuthClient().add(webSocket);
                        } catch (JsonProcessingException e) {
                            e.printStackTrace();
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (viewModel.getClientMap().get(uuid) == null){
                            return;
                        }
                        WebSocket webSocket = Objects.requireNonNull(viewModel.getClientMap().get(uuid)).getWebSocket();
                        ResponseMessage responseMessage = new ResponseMessage.Builder().setType(0).setContent("拒绝连接").build();
                        ObjectMapper objectMapper = new ObjectMapper();
                        try {
                            webSocket.send(objectMapper.writeValueAsString(responseMessage));
                        } catch (JsonProcessingException e) {
                            e.printStackTrace();
                        }
                        Objects.requireNonNull(viewModel.getClientMap().get(uuid)).getWebSocket().close();
                    }
                })
                .setCancelable(false);
        alertDialog.show();
    }
}